import React, { useRef, useState, useEffect } from 'react';
import _ from 'lodash';
import classnames from 'classnames';
import moment from 'moment';
import request from '@/utils/request';
import { interfaceConfig } from '@/config/interfaceConfig';

const Commonaudio = ({ setList_key, songList, list_key, isPlayer, setIsPlayer }) => {
  const audio = useRef(null);
  const [audio_info, setAudio_info] = useState({});
  const [progress, setProgress] = useState(0);
  const [visible, setVisible] = useState({
    volumeBar: false,
  });
  const volumePlayerBar = useRef(null);
  const volumeBar = useRef(null);

  useEffect(() => {
    if (!_.isEmpty(songList)) {
      request
        .get(interfaceConfig.SongPlayer, {
          params: {
            id: list_key,
          },
        })
        .then((ret) => {
          if (ret.code === 200) {
            setAudio_info(ret.data[0]);
          }
        });
    }
  }, [list_key]);

  const onTimeUpdate = (e) => {
    const bar = document.querySelector('.controls-bar');
    const progress = (e.target.currentTime / e.target.duration) * 100;
    setAudio_info((origin) => ({
      ...origin,
      playerTime: moment(e.target.currentTime * 1000).format('mm:ss'),
    }));
    setProgress(progress);
    document.oldX = (progress / 100) * bar.clientWidth;
  };
  const onEnded = (e) => {
    const { songList_id, length, index } = returnInfoKey();

    // 顺序播放
    if (index !== length) {
      setList_key(songList_id[index + 1]);
    } else {
      audio.current.play();
    }
  };

  const navigateClick = (id) => {
    const { songList_id, length, index } = returnInfoKey();
    if (index !== -1) {
      switch (id) {
        case 'prev':
          if (index !== 0) {
            setList_key(songList_id[index - 1]);
          }
          break;
        case 'next':
          if (index !== length) {
            setList_key(songList_id[index + 1]);
          }
          break;
      }
    }
  };
  const returnInfoKey = () => {
    const length = songList.length - 1;
    const index_id = filterKey(list_key)?.id;
    const songList_id = _.map(songList, (item, key) => item.id);
    const index = _.indexOf(songList_id, index_id);
    return {
      length,
      songList_id,
      index,
    };
  };
  const filterKey = (id) => {
    return _.filter(songList, (o) => o.id === id)[0];
  };
  const playerClick = () => {
    if (isPlayer) {
      audio.current.pause();
      setIsPlayer(false);
    } else {
      if (!_.isEmpty(songList)) {
        audio.current.play();
        setIsPlayer(true);
      }
    }
  };
  const playHeadClick = (e) => {
    const bar = document.querySelector('.controls-bar');
    const distance = e.clientX - bar.offsetLeft;

    const progress = (distance / bar.clientWidth) * 100;
    setProgress(progress);
    audio.current.currentTime = (progress / 100) * audio_info.durationV;
  };
  const onMouseDown = (e) => {
    let distX = e.clientX - (document.oldX || 0);
    const bar = document.querySelector('.controls-bar');

    document.onmousemove = (event) => {
      const move_distance = event.clientX - distX;
      audio.current.pause();
      setIsPlayer(false);
      document.oldX = move_distance;

      let progress = (move_distance / bar.clientWidth) * 100;
      progress <= 0 && (progress = 0);
      progress >= 100 && (progress = 100);
      document.progress = progress;
      setProgress(progress);
      return false;
    };
    document.onmouseup = () => {
      if (document.progress) {
        audio.current.currentTime = (document.progress / 100) * audio_info.durationV;
        audio.current.play();
        setIsPlayer(true);
      }
      delete document.progress;
      document.onmousemove = null;
    };
  };
  const onPlayCapture = (e) => {
    setAudio_info((origin) => ({
      ...origin,
      duration: moment(e.target.duration * 1000).format('mm:ss'),
      durationV: e.target.duration,
    }));
  };
  const playerBaronMouseDown = (e) => {
    const iconPlayerBar = volumePlayerBar.current;
    const volume_bar = volumeBar.current;
    const distY = e.clientY - iconPlayerBar.offsetTop;
    document.onmousemove = (event) => {
      let move_distance = event.clientY - distY;
      move_distance >= volume_bar.clientHeight && (move_distance = volume_bar.clientHeight);
      move_distance <= 0 && (move_distance = 0);
      const iconPlayerBarTop = move_distance <= 10 ? 10 : move_distance;
      if (document.volumeBar) {
        iconPlayerBar.style.top = iconPlayerBarTop + 'px';
        volume_bar.style.top = move_distance + 'px';
        let volume = Math.abs((move_distance - volume_bar.clientHeight) / 100);
        volume >= 0.9 && (volume = 1);
        audio.current.volume = volume;
      }

      return false;
    };
    document.onmouseup = () => {
      document.onmousemove = null;
    };
  };

  const onMouseEnter = () => {
    setVisible((origin) => ({
      ...origin,
      volumeBar: true,
    }));
    // 为了解决音量滑动过快bug
    document.volumeBar = true;
  };

  const onMouseLeave = () => {
    setVisible((origin) => ({
      ...origin,
      volumeBar: false,
    }));
    document.volumeBar = false;
  };

  return (
    <div className="audio-player">
      <div className="player-module">
        <div className="controls-left">
          <a className="icon icon-playbar-prev" onClick={() => navigateClick('prev')}></a>
          <a
            className={classnames('icon big-player', {
              'icon-playbar-play': !isPlayer,
              'icon-playbar-pause': isPlayer,
            })}
            onClick={playerClick}
          ></a>
          <a className="icon icon-playbar-next" onClick={() => navigateClick('next')}></a>
        </div>
        <div className="bar-albumImg">
          <img src={filterKey(list_key)?.al?.picUrl || ''} />
        </div>
        <div className="controls-bar">
          <div className="song-info">
            <div className="like-song">{filterKey(list_key)?.name}</div>
            <div className="coding-duration">
              <span>{audio_info?.playerTime || '00:00'}</span>&nbsp;/&nbsp;<span>{audio_info?.duration || '00:00'}</span>
            </div>
          </div>
          <div className="bar">
            <div className="bg" onClick={playHeadClick}></div>
            <div className="progress-bar" style={{ width: progress + '%' }} onClick={playHeadClick}></div>
            <div className="drag-playhead icon icon-playbar-playhead" style={{ marginLeft: progress + '%' }} onMouseDown={onMouseDown}></div>
          </div>
        </div>
        <div className="controls-right">
          <div className="volume" onMouseEnter={onMouseEnter} onMouseLeave={onMouseLeave}>
            <div
              className={classnames('icon', {
                'icon-playbar-silence': audio?.current?.volume === 0,
                'icon-playbar-minvox': audio?.current?.volume !== 0,
              })}
            ></div>
            <div className="volume-panel" style={{ display: visible.volumeBar ? 'block' : 'none' }}>
              <div className="volume-bar">
                <div className="bar" ref={volumeBar}></div>
              </div>
              <span className="icon icon-playbar-progressbottom" ref={volumePlayerBar} onMouseDown={playerBaronMouseDown}></span>
            </div>
          </div>
        </div>
      </div>
      <audio
        ref={audio}
        src={audio_info?.url}
        style={{ display: 'none' }}
        autoPlay
        controls
        onEnded={onEnded}
        onTimeUpdate={onTimeUpdate}
        onPlayCapture={onPlayCapture}
      ></audio>
    </div>
  );
};

export default Commonaudio;
